<?php
class wapi_groups extends wapi_mod_base {
	function _construct(){
		if ($this->firstrun){
			$this->db_create();
		}
	}
	private function db_create(){
		global $wapi;
		$sql = "CREATE TABLE groups (
		id TEXT PRIMARY KEY UNIQUE NOT NULL,
		app_class TEXT NOT NULL,
		group_id TEXT NOT NULL,
		creator_user_id TEXT NOT NULL,
		enabled INTEGER NOT NULL
		)";
		$wapi->db->exec($sql);
		$sql = "CREATE TABLE group_users (
		id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
		group_id TEXT NOT NULL,
		user_id TEXT NOT NULL
		)";
		$wapi->db->exec($sql);
	}
	function user_remove($group,$user_id = null){
		global $wapi;
		if ($user_id = null){
			$user_id = $wapi->user['user_id'];
		}
		$sql = "DELETE FROM group_users WHERE group_id = '$group' AND user_id = '$user_id'";
		if ($wapi->db->exec($sql) == 1)
			return true;
		else
			return false;
	}
	function user_add($group,$user_id = null){
		global $wapi;
		if ($user_id = null){
			$user_id = $wapi->user['user_id'];
		}
		if ($this->user_belongs($group,$user_id))
			return false;
		$sql = "INSERT INTO group_users (group_id,user_id) VALUES ('$group','$user_id')";
		if ($wapi->db->exec($sql) == 1)
			return true;
		else
			return false;
	}
	function user_belongs($group, $user_id = null){
		global $wapi;
		if ($user_id = null){
			$user_id = $wapi->user['user_id'];
		}
		$sql = "SELECT group_id FROM group_users WHERE group_id = '$group' AND user_id = '$user_id'";
		if ($wapi->db->query($sql))
			return true;
		else
			return false;
	}
	function add($group){
		global $wapi;
		$sql = "INSERT INTO groups (group_id,creator_user_id,enabled) VALUES ('$group','{$wapi->user->user_id}',1)";
		if ($wapi->db->exec($sql) == 1)
			return true;
		else
			return false;
	}
	function del($group){
		global $wapi;
		$sql = "DELETE FROM groups WHERE group_id = '$group'";
		if ($wapi->db->exec($sql) == 1)
			return true;
		else
			return false;
	}
	function exists($group){
		global $wapi;
		$sql = "SELECT group_id FROM groups WHERE group_id = '$group'";
		if ($wapi->db->query($sql))
			return true;
		else
			return false;
	}
}
?>